package qc.module.qms.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import qc.common.core.constants.QmsCacheConstant;
import qc.module.qms.entity.QmsPoint;
import qc.module.qms.repository.QmsPointRepository;

import java.util.List;

/**
 * QMS点号Service
 *
 * @author QuCheng Tech
 * @since 2025/9/3
 */
@Service
public class QmsPointService {
    private static final Logger logger = LoggerFactory.getLogger(QmsPointService.class);

    private static final String Cache_Key_Point = QmsCacheConstant.CACHE_KEY_POINT_ENTITY;

    @Autowired
    private QmsPointRepository repository;

    /**
     * 更新缓存，不管是否有缓存数据都进行更新
     *
     * @return java.util.List<qc.module.qms.entity.QmsPoint>
     * @author QuCheng Tech
     * @since 2025/9/11
     */
    @CachePut(value = Cache_Key_Point)//更新缓存，不管是否有缓存数据都进行更新
    public List<QmsPoint> cachePut() {
        logger.debug("cachePut");

        return getAllFromDb();
    }

    /**
     * 清除缓存
     *
     * @return java.lang.String
     * @author QuCheng Tech
     * @since 2025/9/11
     */
    @CacheEvict(value = Cache_Key_Point)//清除缓存
    public void cacheEvict() {
        logger.debug("cacheEvict");
    }

    /**
     * 获取全部点号；有缓存时从缓存获取，没有缓存时从数据库中获取并放入缓存
     *
     * @return java.util.List<qc.module.qms.entity.QmsPoint>
     * @author QuCheng Tech
     * @since 2025/9/11
     */
    @Cacheable(value = Cache_Key_Point)
    public List<QmsPoint> getAllWithCache() {
        logger.debug("getAll");

        return getAllFromDb();
    }

    /**
     * 从数据库中获取全部点号
     *
     * @return java.util.List<qc.module.qms.entity.QmsPoint>
     * @author QuCheng Tech
     * @since 2025/9/11
     */
    public List<QmsPoint> getAllFromDb() {
        logger.debug("getAll 从数据库中查询所有点号信息");
        LambdaQueryWrapper<QmsPoint> wrapper = new LambdaQueryWrapper<>();

        //排序，按站点编码、采集要素编码
        wrapper.orderByAsc(QmsPoint::getStcd).orderByAsc(QmsPoint::getElecode);

        //查询数据
        List<QmsPoint> ens = repository.selectList(wrapper);
        if (ens != null && ens.size() > 0x0)
            return ens;

        return null;
    }
}
